# $language = "python"
# $interface = "1.0"

import os
import sys
import datetime

SCRIPT_TAB = crt.GetScriptTab()
COMMAND = {
	"getTomcatPid"  : "ps x|grep tomcat  |awk '{print $1}'",
	"SSH"           : "/SSH2 /L %s /PASSWORD %s  %s" ,
	"rmTomcatLog"   : "rm -f %s/catalina.out",
	"startTomcat"   : "%s/startup.sh",
	"showTomcatLog" : "tail -f %s/catalina.out",
	"showFileRow"   : "sed -n '%sp' %s" 

}

USER			= "root"
PASSWORD		= "123456"

TOMCAT_HOME		= "/usr/local/apache-tomcat-7.0.39"
TOMCAT_BIN		= TOMCAT_HOME + "/bin"
TOMCAT_LOG		= TOMCAT_HOME + "/logs"
TOMCAT_WEBAPPS	= TOMCAT_HOME + "/webapps"

TARGET_APP      = TOMCAT_WEBAPPS + "/soa-web"
CLASSES_PATH    = TARGET_APP + "/WEB-INF/classes"

USE_FILE_DIALOG = False
 
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#LOG_FILE
LOG_DIRECTORY = os.path.join(
	os.path.expanduser('~'), 'crtlog')

LOG_FILE_TEMPLATE = os.path.join(
	LOG_DIRECTORY, "Command_%(NOW)s_Results.txt")

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#VALIDATE_STRING
MQ_IP			= "mq.parent.host=10.1.1.109"
DETECT_IP		= "systemsDetect.ip =10.1.1.108"

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def execCommand(command) :

	while True:
		if not SCRIPT_TAB.Screen.WaitForCursor(1):
			break

	rowIndex = SCRIPT_TAB.Screen.CurrentRow
	colIndex = SCRIPT_TAB.Screen.CurrentColumn - 1

	prompt = SCRIPT_TAB.Screen.Get(rowIndex, 0, rowIndex, colIndex)
	prompt = prompt.strip()

	SCRIPT_TAB.Screen.Send(command + '\r')

	# Wait for the command to be echoed back to us.
	SCRIPT_TAB.Screen.WaitForString('\r', 1)
	SCRIPT_TAB.Screen.WaitForString('\n', 1)

	result = SCRIPT_TAB.Screen.ReadString(prompt)
	result = result.strip()

	return result

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def killTomcatByForce() :

	result = execCommand(COMMAND["getTomcatPid"])
	
	#kill eachPid 
	tomcatPIdArray = result.split("\r\n")
	for eachPid in tomcatPIdArray :
		execCommand("kill -9 " + eachPid)

	return

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def startupTomcat() :
	cmd = COMMAND["startTomcat"] % (TOMCAT_BIN)
	execCommand(cmd)
	return

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def rmTomcatLog() :
  	cmd = COMMAND["rmTomcatLog"] % (TOMCAT_LOG)
	execCommand(cmd)	
	return

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def showTomcatLog() :
  	cmd = COMMAND["showTomcatLog"] % (TOMCAT_LOG)
	execCommand(cmd)	
	return

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def showTargetFileRowContent(filePath, row) :
	cmd = COMMAND["showFileRow"] % (row, filePath)
	return execCommand(cmd)	

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def checkreplaceMQAndSystemDetectSucceed() :
	configFile = CLASSES_PATH + "/system-config.properties"
	return showTargetFileRowContent(configFile, 22) == MQ_IP and showTargetFileRowContent(configFile, 53) == DETECT_IP
	

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def replaceMQAndSystemDetect() :

	execCommand("sed -i 's/mq.parent.host=10.1.13.233/mq.parent.host=10.1.1.109/g' " + CLASSES_PATH + "/system-config.properties")
	SCRIPT_TAB.Screen.WaitForString('\r', 1)
	SCRIPT_TAB.Screen.WaitForString('\n', 1)

	execCommand("sed -i 's/systemsDetect.ip =10.1.13.231,10.1.13.232/systemsDetect.ip =10.1.1.108/g' " + CLASSES_PATH + "/system-config.properties")
	SCRIPT_TAB.Screen.WaitForString('\r', 1)
	SCRIPT_TAB.Screen.WaitForString('\n', 1)
	return

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def loadHostsFromFile(filePath) :
	if not filePath :
		crt.Dialog.MessageBox("文件路径为空，请重新选择")
		return

	ipFile = open(filePath)
	content = ipFile.readlines()
	hosts = []
	for line in content : 	 
		host = line.strip()
		hosts.append(host)
	ipFile.close()
	return hosts

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def writeLog(filePath, logArray) :
	filep = open(filePath, 'wb+')
	for eachLog in logArray :
		filep.write(eachLog + os.linesep)
	# Close the log file
	filep.close()
	return

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def LaunchViewer(filename):
	try:
		os.startfile(filename)
	except AttributeError:
		subprocess.call(['open', filename])


#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def rightNow() :
	return datetime.datetime.now().strftime("%Y%m%d%H%M%S")

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def NN(number, digitCount):
	# Normalizes a single digit number to have digitCount 0s in front of it
	format = "%0" + str(digitCount) + "d"
	return format % number 
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def Main():

	if not os.path.exists(LOG_DIRECTORY):
		os.mkdir(LOG_DIRECTORY)

	if not os.path.isdir(LOG_DIRECTORY):
		crt.Dialog.MessageBox(
			"Log output directory %r is not a directory" % LOG_DIRECTORY)
		return

	crt.Screen.Synchronous = True
	if USE_FILE_DIALOG :
		filePath = crt.Dialog.FileOpenDialog("请选择IP文件")
	else :
		filePath = "D:/crt_script/ip/my_ip.txt"
	hosts = loadHostsFromFile(filePath)
	if not hosts :
		return

	logFilePath = LOG_FILE_TEMPLATE % {"NOW" : rightNow()}
	crt.Dialog.MessageBox(logFilePath)
	execResults = []

	for (index, line) in enumerate(hosts) : 	 
		host = line.strip()
		cmd = COMMAND["SSH"] % (USER, PASSWORD, host)
		
		if crt.Session.Connected :
			crt.Session.Disconnect()
		crt.Session.Connect(cmd)

		#killTomcatByForce()
		#rmTomcatLog()
		#replaceMQAndSystemDetect()

		succeed = checkreplaceMQAndSystemDetectSucceed()
		execResult = host + "：" + "succeed" if succeed  else "failure"
		execResults.append(execResult)

		#crt.Dialog.MessageBox(str(succeed))
		#startupTomcat()
		#showTomcatLog()

	writeLog(logFilePath, execResults)
	LaunchViewer(logFilePath)
	crt.Screen.Synchronous = False

	#crt.Session.Disconnect()

Main()



